package com.lazycat.backend.service.impl.shop;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lazycat.backend.mapper.GoodMapper;
import com.lazycat.backend.pojo.Good;
import com.lazycat.backend.service.shop.FetchGoodByNameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@Service
public class FetchGoodByNameServiceImpl implements FetchGoodByNameService {
    @Autowired
    private GoodMapper goodMapper;

    @Override
    public JSONObject fetch(String name) {
        QueryWrapper<Good> goodQueryWrapper = new QueryWrapper<>();
        goodQueryWrapper.like(StringUtils.isNotBlank(name), "good_name", name);
        List<Good> goods = goodMapper.selectList(goodQueryWrapper);

        ArrayList<JSONObject> items = new ArrayList<>();

        JSONObject resp = new JSONObject();
        for (Good good : goods) {
            if (good.getBuyerId() == -1) {
                JSONObject item = new JSONObject();
                item.put("img", Base64.getEncoder().encodeToString(good.getGoodImg()));
                item.put("name", good.getGoodName());
                item.put("price", good.getGoodPrice());
                item.put("id", good.getId());
                items.add(item);
            }
        }

        resp.put("items", items);
        resp.put("error_message", "success");
        return resp;
    }
}
